package com.scse.bms.service;

import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import com.scse.bms.domain.UserCaseVO;
import com.scse.bms.domain.UserVO;
import com.scse.bms.entity.UserDO;
import com.scse.bms.mapper.UserRoleMapper;
import com.scse.bms.mapper.UserMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.*;

/**
 * @Title: UserServiceImpl
 * @Author: 吴赠禹
 * @Date: 2020/11/3
 * @Version: 1.0
 * @Description: 用户Service层
 */

@Slf4j
@Service("userService")
@Transactional(rollbackFor = Exception.class)
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserRoleMapper urMapper;

    /**
     * 添加用户
     * 注意事项：用户名、手机号码、姓名唯一。
     * 纠正：姓名不唯一！ 2020-11-23
     *
     * @return
     */
    @Override
    public int addUser(UserDO user) {
        UserDO userDO;
        userDO = userMapper.selectByUsername(user);
        if (userDO != null) {
            return 1001;
        }
        userDO = userMapper.selectByPhoneNum(user);
        if (userDO != null) {
            return 1002;
        }
        // 使用MD5加密
        user.setPassword(DigestUtil.md5Hex(user.getPassword()));
        return userMapper.insert(user);
    }

    /**
     * 查找用户
     * 条件：1、用户名或手机号码（account）；2、密码（pass）
     * 用途：用户登录
     */
    @Override
    public UserVO findUserToLogin(String account, String pass) {
        UserVO user;
        // 1、根据用户名、密码查找
        user = userMapper.selectByUsernameAndPassword(account, pass);
        if (user != null) {
            return user;
        }
        // 2、根据手机号码、密码查找
        user = userMapper.selectByPhoneNumAndPassword(account, pass);
        // 返回可能为null
        return user;
    }

    /**
     * 查询所有用户信息
     * @return
     */
    @Override
    public List<UserVO> selectAllUser(int page, int limit) {
        return urMapper.selectAllUser(page, limit);
    }

    /**
     * 统计所有用户总数
     * @return
     */
    @Override
    public int selectAllUserCount() {
        return userMapper.selectAllUserCount();
    }

    /**
     * 统计符合条件的用户总数
     * @param user
     * @return
     */
    @Override
    public int statAllUserByCase(UserCaseVO user) {
        formatTime(user);
        Map<String, Object> map = new HashMap<>();
        map.put("user", user);
        return userMapper.statAllUserByCase(map);
    }

    /**
     * 查询符合条件的所有用户
     * @param user
     * @return
     */
    @Override
    public List<UserVO> selectAllUserByCase(UserCaseVO user, int page, int limit) {
        formatTime(user);
        Map<String, Object> map = new HashMap<>();
        map.put("user", user);
        map.put("page", page);
        map.put("limit", limit);
        return userMapper.selectAllUserByCase(map);
    }


    /**
     * 处理前端字符串格式日期
     * @param user
     */
    private void formatTime(UserCaseVO user) {
        if (StrUtil.isNotEmpty(user.getDateRange())) {
            log.info("日期不为空，开始格式化");
            String[] date =  user.getDateRange().split(" - ");
            // 使用字符串格式尝试 （也可以）
            user.setStartTime(date[0]);
            user.setEndTime(date[1]);
        }
    }


    /**
     * 用户名是否存在
     * @param username
     * @return
     */
    @Override
    public Integer selectUserNameIfExistById(String username) {
        return userMapper.selectUserNameIfExistById(username);
    }


    /**
     * 更新用户名
     * @param userDO
     * @return
     */
    @Override
    public int updateUserName(UserDO userDO) {
        return userMapper.updateUserNameById(userDO);
    }

    /**
     * 邮箱是否存在
     * @param email
     * @return
     */
    @Override
    public Integer selectEmailIfExistById(String email) {
        return userMapper.selectEmailIfExistById(email);
    }


    /**
     * 更新邮箱
     * @param userDO
     * @return
     */
    @Override
    public int updateEmail(UserDO userDO) {
        return userMapper.updateEmailById(userDO);
    }


    /**
     * 密码是否一致
     * @param userDO
     * @return
     */
    @Override
    public Integer selectPasswordIfCorrect(UserDO userDO) {
        return userMapper.selectUserIfExistByUserNameAndPassword(userDO);
    }

    /**
     * 修改用户密码
     * @param userDO
     * @return
     */
    @Override
    public int updatePassword(UserDO userDO) {
        return userMapper.updatePasswordById(userDO);
    }


    /**
     * 根据用户ID查询用户信息
     * @param id
     * @return
     */
    @Override
    public UserVO selectUserById(Integer id) {
        return userMapper.selectUserById(id);
    }


    /**
     * 获取用户详细信息（session用）
     * @param id
     * @return
     */
    @Override
    public UserVO getUserFullInfoById(Integer id) {
        return userMapper.selectUserForSessionById(id);
    }
}
